package com.aoyama.office.libreoffice.util;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @version V1.0
 * @Title:
 * @Package com.ieslab.pdfview.service.fileservice
 * @Description: TODO
 * @author: zongmoumou
 * @date 2020/10/13
 */
public class PdfUtils {
    public static void wordToPdf(String address, HttpServletResponse response) throws IOException {


//        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//        String tempFilePath = "temp-" + uuid + ".pdf";
//        WorkableConverter converter = new WorkableConverter();
//        ConvertPattern pattern = ConvertPatternManager.getInstance();
//        // 处理本地文件
//        // pattern.streamToStream(new FileInputStream(address), new     FileOutputStream(tempFilePath));
//        // 处理网络文件
//        pattern.streamToStream(FileConvertUtil.getInputStream(address), new FileOutputStream(tempFilePath));
//        pattern.setSrcFilePrefix(DefaultDocumentFormatRegistry.DOCX);
//        pattern.setDestFilePrefix(DefaultDocumentFormatRegistry.PDF);
//        converter.setConverterType(CommonConverterManager.getInstance());
//        boolean result = converter.convert(pattern.getParameter());
//        if (result) {
//            outputPdf(tempFilePath, response);
//            File file = new File(tempFilePath);
//            if (file != null) {
//                file.delete();
//            }
//        }
    }

    public static void outputPdf(String filePath, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        ServletOutputStream out = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(new File(filePath));
            String[] dir = filePath.split("/");
            String fileName = dir[dir.length - 1];
            // 设置响应类型为html，编码为utf-8，处理相应页面文本显示的乱码
            response.setContentType("application/octet-stream");
            // 设置文件头：最后一个参数是设置下载文件名
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (FileNotFoundException e) {

        } finally {
            response.flushBuffer();
            try {
                out.close();
                in.close();
            } catch (NullPointerException e) {

            } catch (Exception e) {

            }
        }

    }
}